package demo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:咭咭熊
 * Date:2021 - 08 - 10
 * Time:18:59
 */
//链表中倒数最后k个节点
public class Test7 {
    /***
     * 链表的倒数第k个节点
     * 思路——使用快慢指针，让fast先走k步，
     * 然后fast和slow一步一步走，
     * 当fast == null的时候，此时slow指向的节点就是倒数第k个节点
     * @param head
     * @param k
     * @return
     */
    public ListNode FindKthToTail(ListNode head,int k){
        if(head == null || k <= 0){
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        //让fast先走k步
        while(fast != null && k > 0){
            fast = fast.next;
            k--;
        }
        //if(fast == null) return null;
        if(k > 0) return  null;//说明链表长度不足够k个
        //此时，fast和slow一起走
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
